import Footer from '@/components/Footer';
import { register } from '@/services/ant-design-pro/api';
import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  // ProFormCaptcha,
  ProFormText,
} from '@ant-design/pro-components';
import { Alert, message, Tabs } from 'antd';
import React, { useState } from 'react';
import { history,  } from 'umi';
import styles from './index.less';
import { Link } from '@umijs/preset-dumi/lib/theme';
const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);
const Register: React.FC = () => {
  const [userLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');

  const handleSubmit = async (values: API.RegisterParams) => {
    /*两次密码是否一样校验*/
    //这里将上面RegisterParams定义的参数取出来
    const { userPassword,checkPassword } = values
    if(userPassword !== checkPassword){
      message.error("两次出输入的密码不一致！")
    }

    try {
      // 注册【register执行注册方法】
      const id = await register({
        ...values,
        type,
      });
      //如果用户存在则显示注册成功
      if (id > 0) {
        const defaultLoginSuccessMessage = '注册成功！';
        message.success(defaultLoginSuccessMessage);
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const { query } = history.location;
        history.push({
          pathname:'/user/login',
          query
        });
        return ;

        // const { redirect } = query as {
        //   redirect: string;
        // };
        //注册成功跳转到登录页面
        // history.push('/user/login?redirect='+ redirect);
        // return;
      }
      // else{
      //   //这里若id小于等于0则登录失败，并抛出异常被下面的catch捕获，执行catch内的方法
      //   // throw new Error(`register error id = ${id}`);
      //   throw new Error();
      // }
    }
    catch (error) {
      const defaultLoginFailureMessage = '注册失败，请重试！';
      message.error(defaultLoginFailureMessage);
    }
  };
  const { status, type: loginType } = userLoginState;

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          //将登录按钮的“登录”替换成“注册”
          submitter={{
            searchConfig:{
              submitText:"注册"
            }

          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="学术导航"
          subTitle={'本人从0-1搭建的学术交流网站'}
          initialValues={{
            autoLogin: true,
          }}
          //表单提交
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane key="account" tab={'账号注册'} />
          </Tabs>

          {status === 'error' && loginType === 'account' && (
            <LoginMessage content={'错误的账号和密码'} />
          )}
          {type === 'account' && (
            <>
              {/*输入用户名的输入框*/}
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入昵称'}
                rules={[
                  {
                    required: true,
                    message: '昵称是必填项！',
                  },
                ]}
              />

              {/*输入账号的输入框*/}
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入账号'}
                rules={[
                  {
                    required: true,
                    message: '账号是必填项！',
                  },
                ]}
              />

              {/*输入密码的而输入框*/}
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                  //这是密码不小于8位
                  {
                    min:8,
                    type:"string",
                    message: '长度不小于8！',
                  },
                ]}
              />

              {/*输入确认密码的输入框*/}
              <ProFormText.Password
                name="checkPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请确认密码'}
                rules={[
                  {
                    required: true,
                    message: '确认密码是必填项！',
                  },
                  //这是密码不小于8位
                  {
                    min:8,
                    type:"string",
                    message: '长度不小于8！',
                  },
                ]}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <Link to="/user/login">返回登录</Link>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Register;
